$(document).ready(function(){
    
    var bonus = $("#ECS_BONUS").find("option:selected").text();
    var integral = $("#ECS_INTEGRAL").attr("value");
    var selProvinces  = $("#selProvinces").find("option:selected").text();
    var need_invoice       = $('input[name="need_invoice"]:checked').val();
    
    
    $("#chosenCoupon").val(bonus);
    $("#chosenIntegral").val(integral);
    if(currentHour > 17){

        $(".tomorrow").html("").css({"cursor":"auto"});         
    }


    $(".peisong_zhiding").focus(function(){
        $(this).parent().parent().find("input").attr("checked","checked");
        $(".peisongshijian").show();
        currents();
    })
    


    $(".shipping-time").click(function(){
        dayAfter = parseInt($(this).attr('day'));
        mid = $(this).attr('mid');
        $(".peisongshijian").hide();
        setShippingDate(dayAfter,mid);
    })

    $("#peisong_time").click(function(){
        currents();               
        $(".peisongshijian").show();

    })

    $("#renyi_time").click(function(){
        $(".peisong_zhiding").val("");                              
        $(".peisongshijian").hide(); 
    })
        
    //在线支付完成页面
    $("#pay_online_btn").click(function(){
                                    
        $aheight = $(document).height(); 
        $awidth = $(document).width(); 
        $docu =  "<div id=\"bg\" style=\"opacity:0.7!important;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=70)!important;height:"+   $aheight+"px;width:100%;max-width:120000px;position:absolute;left:0px;top:0px;background:#000;z-index:4;min-width:1200px;\"></div>";
        $("body").append($docu);
        $("#bg").show();            
        $("#pay_tips").show();
        if ($.browser.msie && ($.browser.version == "6.0") && !$.support.style) { //ie6
            $("#bg").remove(); 
        } 
        if($.browser.msie && $.browser.version=="7.0") {
            $("#bg").remove(); 
        }  
            
    })

    $(".ctl-btn").live('click',function(){

        $(this).hide().prev().toggleClass('explode-btn').parent().next().show();
    });

    $(".fold-parent-btn").live('click',function(){
        $(this).parent().hide().prev().find('.fold-btn').removeClass('explode-btn').siblings().show();
    });

    $(".shippingTab").click(function(){

        $("#shippingInfoText").text('').hide();
        confirmAddress = true;
        confirmShippingTime = false;
        confirmCoupon = false;
        confirmInvoice = false;
        confirmPayment = false;
        checkFlowStep();        

    });

    $("#shippingConfirm").click(function(){
        if ( $("#peisong_time").attr("checked") ){

            shippingText = "花果山物流将于以下时间为您配送："+$("[name=spectime]").val();

        }else{

            shippingText = '花果山物流默认时间配送';

        }
        $("#shippingInfoText").text(shippingText).show();

        if( isAnoymous === false){
            
            $("#benefitInfo").show();
            $("#benefitInfoText").hide();
            $(".benefitTab.ctl-btn").click();
            confirmAddress = true;
            confirmShippingTime = true;
            confirmCoupon = false;
            confirmInvoice = false;
            confirmPayment = false;
        }else{
            $(".invoiceTab.ctl-btn").click();
            confirmAddress = true;
            confirmShippingTime = true;
            confirmCoupon = true;
            confirmInvoice = false;
            confirmPayment = false;  
        }
        
    })

    $(".benefitTab").click(function(){

        $("#benefitInfoText").text('').hide();
        confirmAddress = true;
        confirmShippingTime = true;
        confirmCoupon = false;
        confirmInvoice = false;
        confirmPayment = false;
        checkFlowStep();        
        $("#benefitInfo").show();

    })

    $("#benefitConfirm").click(function(){

        $("#benefitInfoText").text($(".benefit-text:not(:empty)").text()).show();
        $("#benefitInfoText:empty").text('未使用优惠');
        $(".benefitTab").show().prev().toggleClass('explode-btn');
        $("#benefitInfo").hide();
        confirmAddress = true;
        confirmShippingTime = true;
        confirmCoupon = true;
        confirmPayment = false;
                
        if(disableInvoice == 0){
            confirmInvoice = false;
            $(".invoiceTab.ctl-btn").click();
        }else{
            confirmInvoice = true;
            $(".paymentTab.ctl-btn").click();            
        }
    })

    

    $(".invoiceTab").click(function(){
        $("#invoiceInfoText").text('').hide();
        confirmAddress = true;
        confirmShippingTime = true;
        confirmCoupon = true;
        confirmInvoice = false;
        confirmPayment = false;
        checkFlowStep();
    });

    $("#invoiceConfirm").click(function(){
        var need_invoice   = $('input[name="need_invoice"]:checked').val();
        var need_addr      = $('input[name="inv_need_addr"]:checked').val();
        var inv_type       = $('input[name="inv_type"]:checked').val();
        var inv_payee      = $.trim($("#inv_payee").val());
        var inv_content    = $("#inv_content").find("option:selected").text();
        var inv_username   = $.trim($("#inv_username").val());
        var selProvincess  = $("#selProvincess").find("option:selected").val();
        var selCitiess     = $("#selCitiess").find("option:selected").val();
        var selDisctrictss = $("#selDisctrictss").find("option:selected").val(); 
        var inv_address    = $.trim($("#inv_address").val());
        var inv_phone      = $.trim($("#inv_phone").val());
        var invoice_text = "不需要发票";
        if (need_invoice == 1) { //如果需要发票

            if(inv_payee!=''){  //如果发票抬头不为空
                var reg = /^([\w\u4e00-\u9fa5]{1,200})$/g;  //发票抬头,
                if(reg.test(inv_payee)==false)
                {
                    showMsg('发票格式不正确');
                    return false;
                }
                invoice_text = "发票抬头："+inv_payee;
            }else{

                showMsg('发票抬头不能为空');
                return false;
                         
            }
            if(need_addr==1){ //如果需要寄送发票
                invoice_text += " 发票另外寄送，加收￥10";
                if(inv_username != ''){

                    var reg = /^([\w\u4e00-\u9fa5]{1,20})$/g;

                    if(reg.test(inv_username)==false){
                        showMsg('发票收货人姓名的格式不正确');
                        return false;
                    }
                }else{

                    showMsg('发票收货人姓名不能为空');
                    return false;
                }

                if(selProvincess==0){
                    showMsg('请选择省份');
                    return false;
                }
                if(selCitiess==0){
                    showMsg('请选择城市');
                    return false;
                
                }
                if(selDisctrictss==0){
                    showMsg('请选择区域');
                    return false;
                }
                if(inv_address == ''){
                    showMsg('收货地址不能为空');
                    return false;
                }
                if(inv_phone != ''){
                    var reg = /^1[3458]\d{9}$/g;  //手机号码的验证 11位，
                    if(reg.test(inv_phone)==false){
                    
                        showMsg('手机的格式不正确');
                        return false;       
                    }

                }else{

                    showMsg('手机号码不能为空');
                    return false;
                  
                }             
            }
        }
        $("#invoiceInfoText").text(invoice_text).show();
        $(".invoiceTab").show().prev().toggleClass('explode-btn');
        $("#invoiceInfo").hide();

        confirmAddress = true;
        confirmShippingTime = true;
        confirmCoupon = true;
        confirmInvoice = true;
        confirmPayment = false;        
        checkFlowStep();
        $(".paymentTab.ctl-btn").click();
    })

    $(".paymentTab").click(function(){
        $("#paymentInfoText").text('').hide();
        confirmAddress = true;
        confirmShippingTime = true;
        confirmCoupon = true;
        confirmInvoice = true;
        confirmPayment = false;        
    })

    $("#paymentConfirm").click(function(){
        var payment = $('input[name="payment"]:checked').val();
        if (mobile_confirm =="1" || payment > 1)
        {
        
            if(payment == 1){
                paymentText = '货到付款';                
            }
            if(payment == 2){
                paymentText = '支付宝';
                
            }
            confirmAddress = true;
            confirmShippingTime = true;
            confirmCoupon = true;
            confirmInvoice = true;
            confirmPayment = true;                  
            $("#paymentInfoText").text(paymentText).show();
            $(".paymentTab").show().prev().toggleClass('explode-btn');
        }
        else
        {   
           
            $('#mobile_confirm_window').show();
            showMsg('请先验证手机');
        }
    })


    $(".addressTab").live('click',function(){

        $("#peisongdizhi_abstract").text('').hide();        
        $(".set-address-btn").show();
        confirmAddress = false;
        confirmShippingTime = false;
        confirmCoupon = false;
        confirmInvoice = false;
        confirmPayment = false;        
        checkFlowStep();
    })

    //选择地址
    $(".user-address-list,#radio_current_address").live('click',function(){
        $(".set-address-btn").show();
        $("#peisong_update_address").hide();
    });

    
    if(need_invoice == 0){
        $("#is_need_invoice").hide();
        $("#fapiao_queren_no").show();
        $("#inv_need_addr").attr("checked","checked");
        changefreight(0);
        
    }else{
        changefreight(0);           
        $("#is_need_invoice").show();
        $("#fapiao_queren_no").show();
       
    }

    $("input:radio[name=voucher]").click(function(){
        if($(this).val() == 1){

            $("#couponInfo").show();
            $("#bonus_image_captcha").attr({src:'captcha.php?captcha_activate=1&'+Math.random()})
            $("#giftcard_info").hide();
            $("input:checkbox[name='giftcardID[]']").each(function(){
                $(this).prop('checked',false);
            });
        }else{
            
            $("#ECS_BONUS").find("option").eq(0).prop('selected',true);
            $("#giftcard_image_captcha").attr({src:'captcha.php?captcha_activate=1&'+Math.random()})
            $("#giftcard_info").show(); 
            $("#couponInfo").hide();
        }
    })

    $("[name=need_invoice]").click(function(){
        if($(this).attr("vid")==0){
            $("#is_need_invoice").hide();
            $("#inv_need_addr").attr("checked","checked");
            $("#fapiao_queren_no").show();
            changefreight(0);
        }else {
            $("#is_need_invoice").show();
            $("#fapiao_queren_no").show();
            $("#need_address").hide();
            changefreight(0);
        }
    })
    

    $("[name=inv_need_addr]").click(function(){
        if($(this).attr("vid")==0){
            $("#need_address").hide();
            changefreight(0);
        }else {
            $("#need_address").show();
            changefreight(10);
        }
    })
    
    //  sshi 取得收货地址的 省 部分
    
    //region.changed(document.getElementById('selCities'), 3, 'selDisctricts')
    /*
    document.getElementById('selCities').selectedIndex = '1';
    region.loadRegions('深圳', 3, 'selDisctricts');
    */

    //支付方式选择mike
    $("#pay_receipt").click(function(){
        if ( mobile_confirm === "1"){
            $('#mobile_confirm_window').hide();
        }else{
            $aheight = $(document).height(); 
            $awidth = $(document).width(); 
            $docu =  "<div id=\"bg\" style=\"opacity:0.7!important;filter:progid:DXImageTransform.Microsoft.Alpha(Opacity=70)!important;height:"+   $aheight+"px;width:100%;max-width:120000px;position:absolute;left:0px;top:0px;background:#000;z-index:4;min-width:1200px;\"></div>";
            $("body").append($docu);
            $("#bg").show();             
            $('#mobile_confirm_window').show();
        }
        $('input:radio[name=pay_online]').prop('checked',false);
    })
    $("#pay_online").click(function(){
        $('#mobile_confirm_window').hide();
        $('input:radio[name=payment]').prop('checked',false);
        $('input:radio[rel=payment]').prop('checked',true);
    })
    $("[rel=payment]").click(function(){
        $('#mobile_confirm_window').hide();
        $('input:radio[name=pay_online]').prop('checked',true);
    })    

});

function intval_filter(goods_number){
	if( isNaN(goods_number)){
		goods_number ='1';
	}
	goods_number = Math.ceil(goods_number);
	if( eval(goods_number) < 1){
		goods_number = '1';	
	}	
	return goods_number;
}

function changenum(rec_id, diff)
{
    var goods_number =$$('goods_number_' + rec_id).value;
	goods_number = intval_filter(goods_number);
	goods_number = Number(goods_number) + Number(diff);
	$$('goods_number_' + rec_id).value = goods_number;		
    change_goods_number(rec_id,goods_number);
}
function change_goods_number(rec_id, goods_number)
{   
	goods_number = intval_filter(goods_number);
	Ajax.call('flow.php?step=ajax_update_cart', 'rec_id=' + rec_id +'&goods_number=' + goods_number, change_goods_number_response, 'POST','JSON'); 				
}


function change_goods_number_response(result)
{    
	//alert('change_goods_number_response start  = ' + result.goods_amount + ' result.favourable_exist = ' +result.favourable_exist);    
    if (result.error == 0)
    {
        var rec_id = result.rec_id;
        $$('goods_number_' +rec_id).value = result.goods_number;//更新数量
        $$('goods_subtotal_' +rec_id).innerHTML = result.goods_subtotal;//更新小计
		
		// sshi 更新积分数量
		var subtotal = result.goods_subtotal;
		//alert(' give_integral = ' + result.give_integral );
		if(result.give_integral < 0 ) {
			subtotal = subtotal.replace('￥','');
			subtotal = subtotal.replace('元','');
			subtotal = eval(subtotal.replace(' ',''));						
		}else{
			subtotal = result.give_integral;
		}
		$$('goods_give_integral_' +rec_id).innerHTML = subtotal;
		
		// sshi 更新积分小计（总数）
		var items = document.getElementsByName("item_give_integral");
		var total_integral = 0;
		for(var i=0;i<items.length;i++){
			total_integral = eval(total_integral)+ eval(items[i].value);
		}
		//ocument.getElementById('cart_total_integral').innerHTML = '+'+total_integral;
		//alert('cart_total_integral = ' + total_integral );

		// maojy
		$$('min_goods_number_' +rec_id).value = result.goods_number;//更新迷你购物车数量
		$("#goods_amount").html(result.goods_amount);
		
		
        if (result.goods_number <= 0)
        {// 数量为零则隐藏所在行
            $$('tr_goods_' +rec_id).style.display = 'none';
            $$('tr_goods_' +rec_id).innerHTML = '';
        }
        //$$('total_desc').innerHTML =result.total_desc;//更新合计
        if ($$('ECS_CARTINFO'))
        {//更新购物车数量
           $$('ECS_CARTINFO').innerHTML = result.cart_info;
        }
        
        $$('big_cart').innerHTML = result.big_cart;
        $$('shopping_money').innerHTML=result.goods_amount;
		//$$('shopping_money').innerHTML = result.goods_subtotal;			//  sshi 购物车总价
        
        if(result.favourable_exist == '0'){
			var cart_fav = document.getElementById('cart_favourables');
			if( cart_fav != undefined )	document.getElementById('cart_favourables').style.display = 'none';
			
        }else if(result.favourable_exist == '1'){
			document.getElementById('cart_favourables').style.display = 'block';
			$$('cart_favourables').innerHTML = result.cart_favourables;
		}
        
    }
    else if (result.message != '')
    {
        alert(result.message);
    }                
}

function cartalert()
{
    showMsg('购物车为空');	
}

function validateCell()
{
    var code=document.getElementsByName('validateCode')[0].value;
	if(code == ""){
        showMsg('请输入验证码')
	}else{
		Ajax.call('user.php','act=act_bind_cell&code='+code,validateCellResp,"GET","TEXT");
	}
    
    
}

function validateCellResp(result)
{
    var res=$.evalJSON(result);
    if (res.error !=0)
    {
        showMsg('验证码错误，请重新发送验证码。')
    }
    else
    {
        showMsg('验证成功');
    	$("#pay_all_main").hide();
		$("#mobile_confirm_window").hide();
        $("#bg").remove()
    	//$("#validateCellPhone").html("");
    	mobile_confirm="1";
    }
}

function sendCode()
{
    var cell=document.getElementsByName('cellphonenumber')[0].value;
	if(isMobelphone(cell) == false){
		showMsg('请输入正确的手机号');
	}else{
		Ajax.call('user.php','act=act_send_code&cell='+cell,sendCodeResp,"GET","TEXT");
	}
}

function sendCodeResp(result)
{
    var res=$.evalJSON(result);
	$("#send_phone_code").hide().delay(60000).show(0);
	$("#send_phone_code2").show().delay(60000).hide(0);
    showMsg(res.content+",60秒后可重新验证");
}
            
			
function confirmInvoiceInfo(){
	

    var need_invoice   = $('input[name="need_invoice"]:checked').val();
    var need_addr      = $('input[name="inv_need_addr"]:checked').val();
    var inv_type       = $('input[name="inv_type"]:checked').val();
    var inv_payee      = $.trim($("#inv_payee").val());
    var inv_content    = $("#inv_content").find("option:selected").text();
    var inv_username   = $.trim($("#inv_username").val());
    var selProvincess  = $("#selProvincess").find("option:selected").val();
    var selCitiess     = $("#selCitiess").find("option:selected").val();
    var selDisctrictss = $("#selDisctrictss").find("option:selected").val(); 
    var inv_address    = $.trim($("#inv_address").val());
    var inv_phone      = $.trim($("#inv_phone").val());
    var invoice_text = "不需要发票";
    if (need_invoice == 1) { //如果需要发票

        if(inv_payee!=''){  //如果发票抬头不为空
            var reg = /^([\w\u4e00-\u9fa5]{1,200})$/g;  //发票抬头,
            if(reg.test(inv_payee)==false)
            {
                showMsg('发票格式不正确');
                return false;
            }
            invoice_text = "发票抬头："+inv_payee;
        }else{

            showMsg('发票抬头不能为空');
            return false;
                     
        }
        if(need_addr==1){ //如果需要寄送发票
            invoice_text += " 发票另外寄送，加收￥10";
            if(inv_username != ''){

                var reg = /^([\w\u4e00-\u9fa5]{1,20})$/g;

                if(reg.test(inv_username)==false){
                    showMsg('发票收货人姓名的格式不正确');
                    return false;
                }
            }else{

                showMsg('发票收货人姓名不能为空');
                return false;
            }

            if(selProvincess==0){
                showMsg('请选择省份');
                return false;
            }
            if(selCitiess==0){
                showMsg('请选择城市');
                return false;
            
            }
            if(selDisctrictss==0){
                showMsg('请选择区域');
                return false;
            }
            if(inv_address == ''){
                showMsg('收货地址不能为空');
                return false;
            }
            if(inv_phone != ''){
                var reg = /^1[3458]\d{9}$/g;  //手机号码的验证 11位，
                if(reg.test(inv_phone)==false){
                
                    showMsg('手机的格式不正确');
                    return false;       
                }

            }else{

                showMsg('手机号码不能为空');
                return false;
              
            }             
        }
    }
    $("#invoiceInfoText").text(invoice_text).show();
    $(".invoice-confirm-btn").parent().hide().prev().find('.fold-btn').removeClass('explode-btn').siblings().show();
    return true;

}

        
             
//把外收发票的邮费提交
function changefreight(freight){
    Ajax.call('flow.php?step=order_freight','freight=' + freight,changefreightResponse,"POST","TEXT");
}
function changefreightResponse(result)
{
    var res   = $.evalJSON(result);
    $("#freight").html(res.freight);
    $("#amount_formated").html(res.amount_formated);
}
		
function change_consignee_address(){
	var new_address = document.getElementById('radio_new_address').checked;
	if(new_address){
		document.getElementById('peisong_update_address').style.display='block';
		document.getElementById('selected_address').value = '';		// 清空默认地址id
		
		document.getElementById('consignee').value = '';
		document.getElementById('ship_info_address').value = '';
		document.getElementById('ship_info_telephone').value = '';		
		document.getElementById('peisongdizhi_abstract').value = '';
        $(".set-address-btn").hide();
		
	}else{
		document.getElementById('peisong_update_address').style.display='none';
		
	}
}



function change_default_address(obj){

	document.getElementById('selected_address').value = obj.value;
	document.getElementById('peisong_update_address').style.display = 'none';
	document.getElementById('peisongdizhi_input').style.display = 'none';
	document.getElementById('peisongdizhi_abstract').style.display = 'block';
	document.getElementById('peisongdizhi_input').style.display='none';
		

	var itemId = document.getElementById('selected_address').value;
	var address_absctract = document.getElementById('address_' + itemId).value;
	document.getElementById('peisongdizhi_abstract').innerHTML = address_absctract;
	Ajax.call('flow.php?step=change_consignee', 'address_id=' + itemId , change_consignee_resp, "POST", "TEXT");
}

function setAddress(){

        itemId = $(".user-address-list:checked").val();

        setSelectedAddress(itemId);
}

function change_consignee_resp(result)
{
	var res = $.evalJSON(result);
 
  	var mzone = document.getElementById("ECS_ORDERTOTAL");
    mzone.innerHTML = res.content;
    confirmAddress = true;
    confirmShippingTime = false;
    confirmCoupon = false;
    confirmInvoice = false;
    confirmPayment = false;
    $(".shippingTab.ctl-btn").click();
    

}

function save_consignee()
{
	
	if( $("#radio_new_address").prop('checked') == false ){


		
		var itemId = document.getElementById('selected_address').value;
        setSelectedAddress(itemId)
		exit;	
	}

	consignee 	= get_elements_value('consignee');
	province	= filterInt(get_elements_value('province'));
	city 		= filterInt(get_elements_value('city'));
	district 	= filterInt(get_elements_value('district'));
	mobile 		= get_elements_value('mobile');
	address 	= get_elements_value('address');					
	
	var check_msg = check_consign_address( consignee, province, city, district, mobile, address );
	
	if(consignee!='')
	{
	   var reg=/^([\w\u4e00-\u9fa5]{1,20})$/g; 
			   if(reg.test(consignee)==false)
			   {
					showMsg('姓名的格式不正确')			
					return;
				}else{
				 	if(address!='')
					{
					    	if(mobile!='')
							{
							 	   var reg= /^1[3458]\d{9}$/g;  //手机号码的验证 11位，
								   if(reg.test(mobile)==false)
								   {
									
										showMsg('手机的格式不正确');
										return;
										
									}
							}else
							{
							    showMsg('手机号不能为空');
								return;			
								
							}
					
					}else
					{
						showMsg('地址不能为空');
						return;
					
					
					}
				}	
				
				
	} else {

		showMsg('姓名不能为空')			
		return;
	
	}
	

/*	consignee_list = get_elements_value('consignee_list');	
	alert('consignee_list = ' + consignee_list);*/
/*	alert('ajax call: ' + 'consignee=' + consignee + '&mobile=' + mobile + '&province=' + province
			  				+'&city='+city+'&district='+district+'&address='+address);*/

	$("[name=peisongdizhi_name_1]").show();
	Ajax.call('flow.php?step=save_consignee', 
			  'consignee=' + consignee + '&mobile=' + mobile + '&province=' + province
			  				+'&city='+city+'&district='+district+'&address='+address, consignee_response, 
			  "POST", "TEXT");
}

function consignee_response(result)
{

	var res = $.evalJSON(result);

	/*如果没有登录，仅仅刷新地址而已*/
	if(res.use_cookie == '1'){
		document.getElementById('local_address').value = '1';		// 更新flag
				
		document.getElementById('temp_user_address_full_addr').innerHTML = res.full_address;
		document.getElementById('temp_user_address_consignee').innerHTML = res.consignee;
		document.getElementById('temp_user_address_mobile').innerHTML = res.mobile;		
		//document.getElementById('temp_user_address').style.display = 'block';
		document.getElementById('radio_current_address').checked = 'checked';
		
		document.getElementById('peisongdizhi_abstract').innerHTML = res.consignee +'    ' 
																	+ res.full_address+'    ' +res.mobile;
																	
		document.getElementById('peisong_update_option').style.display = 'block';	
		document.getElementById('temp_user_address').style.display = 'block';														
		
		document.getElementById('peisongdizhi_input').style.display = 'none';	
	}
	else{
		var mzone = document.getElementById("HGS_CONSIGNEE");
		mzone.innerHTML = res.content;		
		document.getElementById('btn_modify_address').style.display = 'inline';		//sshi 
	}
	var total = document.getElementById("ECS_ORDERTOTAL");
	total.innerHTML = res.order_total;
	document.getElementById('peisongdizhi_abstract').style.display = 'block';
	document.getElementById('peisong_update_address').style.display='none';
    confirmAddress = true;
    confirmShippingTime = false;
    confirmCoupon = false;
    confirmInvoice = false;
    confirmPayment = false;
    $(".set-address-btn").hide();
    $("#btn_modify_address").show().prev().toggleClass('explode-btn');
    $(".shippingTab.ctl-btn").click();
	
}


// sshi 删除地址的回调
function delete_consignee_response(result)
{
	var res = $.evalJSON(result);

	/*如果没有登录，仅仅刷新地址而已*/
	if(res.use_cookie == '1'){
				
		document.getElementById('temp_user_address_full_addr').innerHTML = res.full_address;
		document.getElementById('temp_user_address_consignee').innerHTML = res.consignee;
		document.getElementById('temp_user_address_mobile').innerHTML = res.mobile;		
		document.getElementById('temp_user_address').style.display = 'block';
		document.getElementById('radio_current_address').checked = 'checked';
	}
	else{
		var mzone = document.getElementById("HGS_CONSIGNEE");
		mzone.innerHTML = res.content;		
	}
	var total = document.getElementById("ECS_ORDERTOTAL");
    total.innerHTML = res.order_total;
	document.getElementById('peisong_update_address').style.display='none';

	//alert(' res.full_address = ' + res.full_address);	
	if(res.full_address == ''){
		document.getElementById('peisongdizhi_input').style.display = 'block';
		document.getElementById('peisong_update_address').style.display='block';
			
	}	
}

function peisong_display(){
	document.getElementById('peisongdizhi_input').style.display = 'block';
	document.getElementById('peisong_update_address').style.display='block';
	document.getElementById('peisong_update_address').style.display='none';
	document.getElementById('peisongdizhi_abstract').style.display='none';
}



function delete_consignee(consignee_id)
{
	Ajax.call('flow.php?step=delete_consignee','id='+consignee_id,delete_consignee_response,"POST","TEXT");
	//Ajax.call('flow.php?step=delete_consignee','id='+consignee_id,delete_consignee_response,"POST","TEXT");
}




// sshi 删除cookie里面存的地址
function delete_consignee_in_cookie()
{
	setCookie('temp_user_consignee','',0);
	
	document.getElementById('temp_user_address_full_addr').innerHTML = '';
	document.getElementById('temp_user_address_consignee').innerHTML = '';
	document.getElementById('temp_user_address_mobile').innerHTML = '';
	document.getElementById('radio_new_address').checked = 'checked';
	document.getElementById('temp_user_address').style.display = 'none';
	
	document.getElementById('peisongdizhi_input').style.display = 'block';
	document.getElementById('peisong_update_address').style.display='block';	
	document.getElementById('peisong_update_option').style.display = 'block';

	document.getElementById('selected_address').value = '';		// 清空默认地址id
	
	document.getElementById('consignee').value = '';
	document.getElementById('ship_info_address').value = '';
	document.getElementById('ship_info_telephone').value = '';	
	document.getElementById('peisongdizhi_abstract').innerHTML = '';	
	document.getElementById('local_address').value = '';	
	Ajax.call('flow.php?step=delete_consignee','id=0',delete_consignee_in_cookie_response,"POST","TEXT");
		
}

function delete_consignee_in_cookie_response(result)
{
	var res = $.evalJSON(result);
	
	var total = document.getElementById("ECS_ORDERTOTAL");
    total.innerHTML = res.order_total;
    $("set-address-btn").hide();
}

function setCookie(c_name, value, expiredays){
 　　　　var exdate=new Date();
 　　　　exdate.setDate(exdate.getDate() + expiredays);
 　　　　document.cookie=c_name+ "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

// sshi 对数字进行过滤
function filterInt(str){
	if( isNaN(str) || str.length >5 ){
		return '';	
	}else{
		return str;	
	}
}

// sshi 检查省市区和其他地址信息
function check_consign_address( consignee, province, city, district, mobile, address ){
	var msg = Array();
	if( consignee=='' ) msg.push('姓名不能为空');
	if( province=='' ) 	msg.push('省名不能为空');	
	if( city=='' ) 		msg.push('市名不能为空');
	if( district=='' ) 	msg.push('区名不能为空');	
	if( mobile=='' ) 	msg.push('电话号码不能为空');
	if( address=='' ) 	msg.push('地址不能为空');				
	
	var message = msg.join("\n");
	return message;
}




// sshi 通过元素名字取得页面元素的值，如果是radio button，取得被check的那个值
function get_elements_value( iName ){
	var item = Array();
	item = document.getElementsByName(iName);
	var iValue = '';
	if(item.length > 1){
		for(var i=0;i<item.length;i++){
			if( item[i].checked =='true' ){
				iValue = item[i].value;
			}
		}
	}else{
		iValue = item[0].value;
	}
	return iValue;
}

function addSingleFavourableToCart(act_id,gift_id,total_price){
	Ajax.call('flow.php?step=add_single_favourable','act_id=' + act_id + '&gift=' + gift_id +
													'&total_price=' + total_price
													,addSingleFavourableToCart_Response,"POST","TEXT");
}

function addSingleFavourableToCart_Response(result){

	var res = $.evalJSON(result);
	
	//alert('1 ' + res.big_cart);
	//alert('2 ' + res.cart_favourables);
	
	document.getElementById('big_cart').innerHTML = res.big_cart;
	document.getElementById('ECS_CART').innerHTML = res.cart;
	document.getElementById('cart_favourables').innerHTML = res.cart_favourables;
	
	
	//$$('big_cart').innerHTML = res.big_cart;
	//$$('favourable_list').innerHTML = res.cart_favourables;
	
	if(res.error != '0'){
		$("#tips_big_div").show();
		$("#tips_word").html(res.message);			
	}
	else{
		document.getElementById('cart_favourables').style.display = 'none';
	}
}

/**
 * 把单个赠品添加到购物车里
 * @param act_id	int		活动id
 * @param gift_id	int		赠品的商品id
 * @param total_price	int	购物车内的商品总价值
 * @return 无
 * 
 * */
function addSingleFavourableToCart(act_id,gift_id,total_price){
	Ajax.call('flow.php?step=add_single_favourable','act_id=' + act_id + '&gift=' + gift_id +
													'&total_price=' + total_price
													,addSingleFavourableToCart_Response,"POST","TEXT");
}


/**
 * 把单个赠品添加到购物车的回调函数
 *		如果有错误，不能添加，则弹窗显示错误信息
 *		添加成功，则隐藏赠品模块，刷新赠品模块，购物车模块和迷你购物车模块 		
 * 
 * */
function addSingleFavourableToCart_Response(result){

	var res = $.evalJSON(result);
	document.getElementById('big_cart').innerHTML = res.big_cart;
	document.getElementById('ECS_CART').innerHTML = res.cart;
	document.getElementById('cart_favourables').innerHTML = res.cart_favourables;
	
	if(res.error != '0'){
		$("#tips_big_div").show();
		$("#tips_word").html(res.message);			
	}
	else{
		document.getElementById('cart_favourables').style.display = 'none';
	}
}










//wwzedit 优惠券显示切换
function toggleBonusInfo()
{
	$("#couponInfo").toggle();
	checkBenefitInfoText();
	
	if( $("#checkoutBonusPlus").is(":visible") === true ){
		$("#checkoutBonusPlus").hide();
		$("#checkoutBonusMinus").show();
	}
	else{
		$("#checkoutBonusPlus").show();
		$("#checkoutBonusMinus").hide();
	}
}




//点击出现时间选择窗口 
$(function(){

    

		 
})
//点击出现配送时间段。


function setSelectedAddress(addressId){

    $("#peisong_update_address,#peisongdizhi_input").hide();
    $("#btn_modify_address").show().prev().toggleClass('explode-btn');

    if(isAnoymous == false){
        address_absctract = $("#address_"+addressId).val();
        $("#selected_address").val(itemId);
        $("#peisongdizhi_abstract").text(address_absctract).show();
        Ajax.call('flow.php?step=change_consignee', 'address_id=' + addressId , change_consignee_resp, "POST", "TEXT");

    }else if(isAnoymous == true){

        $("#peisongdizhi_abstract").text(function(){
            return $("#temp_user_address_consignee").text()+' '+$("#temp_user_address_full_addr").text()+' '+$("#temp_user_address_mobile").text();
        }).show();

        confirmAddress = true;
        confirmShippingTime = false;
        confirmCoupon = false;
        confirmInvoice = false;
        confirmPayment = false;
        $(".shippingTab.ctl-btn").click();        
    }
    
}


//增值税发票
function putong(){
	$("[name=fapiao_name]").hide();
	$(".putongfapiao").show();
}

function zengzhi(){
	$("[name=fapiao_name]").hide();
	$(".zengzhishuifapiao").show();
	
}


function setShippingDate(dayAfter,middle){
    if(currentHour > 17 && dayAfter == 1 ){
        dayAfter = 2;
    }
    switch(dayAfter){
        case 1:
            dayCount = 1;
            dayText = '(明天)';
            break;
        case 2:
            dayCount = 2;
            dayText = '(后天)';
            break;
        case 3:
            dayCount = 3;
            dayText = '(大后天)';
            break;
        default:
            dayCount = 1;
            dayText = '(明天)';
    }
    switch(middle){
        case 'am':
            shippingTime = '09:00-18:00';
            break;
        case 'pm':
            shippingTime = '18:00-22:00';
            break;        
    }
    var dd = new Date();
    dd.setDate(dd.getDate()+dayCount);
    var y = dd.getFullYear();
    var m = dd.getMonth()+1;
    var d = dd.getDate();
    var str = y + "-" + m + "-" + d + dayText + shippingTime;
    $(".peisong_zhiding").val(str);
}

function GetDateStr(AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
    var y = dd.getFullYear();
    var m = dd.getMonth()+1;//获取当前月份的日期
    var d = dd.getDate();
    return m+"-"+d;
}
function currents(){
	$(".peisong_date_two_jintian").html(GetDateStr(1));
	$(".peisong_date_two_mingtian").html(GetDateStr(2));
	$(".peisong_date_two_houtian").html(GetDateStr(3));

}

function showMsg(msg){
    $("#tips_big_div").show();
    $("#tips_word").html(msg);    
}

function checkFlowStep(){
    if(confirmAddress == false){

        $(".shippingTab,.benefitTab,.invoiceTab,.paymentTab,#shippingInfo,#benefitInfo,#invoiceInfo,#paymentInfo").hide(0,function(){

            $("#shippingInfoText,#benefitInfoText,#invoiceInfoText,#paymentInfoText").text(function(){
                return $(this).attr('origin');
            }).show();
            
        }).prev().removeClass('explode-btn')
        return ;
    }
    if(confirmShippingTime == false){
        $(".benefitTab,.invoiceTab,.paymentTab,#benefitInfo,#invoiceInfo,#paymentInfo").hide(0,function(){
            $("#benefitInfoText,#invoiceInfoText,#paymentInfoText").text(function(){
                return $(this).attr('origin');
            }).show();
        }).prev().removeClass('explode-btn')
        return ;
    }
    if(confirmCoupon == false){
        $(".invoiceTab,.paymentTab,#invoiceInfo,#paymentInfo").hide(0,function(){
            $("#invoiceInfoText,#paymentInfoText").text(function(){
                return $(this).attr('origin');
            }).show();
        }).prev().removeClass('explode-btn')
        return ;
    }
    if(confirmInvoice == false){

        $(".paymentTab,#paymentInfo").hide(0,function(){
            $("#paymentInfoText").text(function(){
                return $(this).attr('origin');
            }).show();
        }).prev().removeClass('explode-btn')

        return;
    }


}
